<html>
<head>
    <title>SSE</title>
</head>
<body>
<button type="button" onclick="closeSse()">Close</button>
<hr style="margin: 2px; padding: 0px 0px;"/>
<ul id="list"></ul>
</body>
<script>
    const evtSource = new EventSource(`/sse/events/${Date.now()}`) ;
    evtSource.onmessage = (event) => {
        const newElement = document.createElement("li") ;
        const eventList = document.getElementById("list") ;
        newElement.innerHTML = "接收到消息: " + event.data ;
        eventList.appendChild(newElement) ;
    };
    evtSource.onopen = (event) => {
        console.log('建立连接...')
    };
    evtSource.onerror = (event) => {
        console.error("发生错误：", event) ;
    };
    function closeSse() {
        evtSource.close() ;
    }

    // 监听指定事件类型消息
    evtSource.addEventListener("chat", (event) => {
        const newElement = document.createElement("li");
        const eventList = document.getElementById("list");

        newElement.innerHTML = "chat message: " + event.data;
        eventList.appendChild(newElement);
    });

</script>
</html>